package com.panda.autotest.core.mybatis.plugin;

import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;

import java.text.MessageFormat;

import org.mybatis.generator.codegen.mybatis3.IntrospectedTableMyBatis3Impl;

/**
 * 可以通过MBG1.3.4+版本提供的table元素的mapperName属性设置统一的名称，使用{0}作为实体类名的占位符。
 */
public class CustomMyBatis3Plugin extends IntrospectedTableMyBatis3Impl {

	private static final String PREFIX = "T";

	@Override
	protected String calculateMyBatis3XmlMapperFileName() {
		StringBuilder sb = new StringBuilder();
		if (stringHasValue(tableConfiguration.getMapperName())) {
			String mapperName = tableConfiguration.getMapperName();
			int ind = mapperName.lastIndexOf('.');
			if (ind != -1) {
				mapperName = mapperName.substring(ind + 1);
			}
			sb.append(MessageFormat.format(mapperName, this.updateDomainObjectName()));
			sb.append(".xml");
		} else {
			sb.append(fullyQualifiedTable.getDomainObjectName());
			sb.append("Mapper.xml");
		}
		return sb.toString();
	}

	private String updateDomainObjectName() {
		String objName = fullyQualifiedTable.getDomainObjectName();
		if (objName.startsWith(PREFIX)) {
			objName = objName.substring(PREFIX.length());
		}
		try {
			java.lang.reflect.Field field = fullyQualifiedTable.getClass().getDeclaredField("domainObjectName");
			field.setAccessible(true);
			field.set(fullyQualifiedTable, objName);
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return objName;
	}

	@Override
	protected void calculateJavaClientAttributes() {
		if (context.getJavaClientGeneratorConfiguration() == null) {
			return;
		}

		StringBuilder sb = new StringBuilder();
		// 设置接口类型
		sb.setLength(0);
		sb.append(calculateJavaClientInterfacePackage());
		sb.append('.');
		sb.append(this.updateDomainObjectName());
		sb.append("Dao");
		setDAOInterfaceType(sb.toString());
		// 设置mapper类型
		sb.setLength(0);
		sb.append(calculateJavaClientInterfacePackage());
		sb.append('.');
		if (stringHasValue(tableConfiguration.getMapperName())) {
			sb.append(MessageFormat.format(tableConfiguration.getMapperName(), this.updateDomainObjectName()));
		} else {
			sb.append(this.updateDomainObjectName());
			sb.append("Mapper");
		}
		setMyBatis3JavaMapperType(sb.toString());
	}
}